<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="材质名称" prop="pathName">
        <el-select
          v-model="queryParams.pathName"
          filterable
          clearable
          default-first-option
          placeholder="请选择材质名称">
          <el-option v-for="item in matMgmtList" :key="item.id" :label="item.matName" :value="item.id" @keyup.enter.native="handleQuery"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['business:pathRel:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          :disabled="single"
          @click="handleDelete"
          v-hasPermi="['business:pathRel:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-refresh"
          @click="handleRefreshCache"
          v-hasPermi="['business:pathRel:refreshCache']"
        >刷新缓存</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div :style="'height:' + divHeight + 'px'">
      <el-table
        ref="pathTreeTable"
        v-if="refreshTable"
        v-loading="loading"
        :data="pathRelList"
        row-key="id"
        :default-expand-all="isExpandAll"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        @select="handleRowSelect"
      >
        <el-table-column type="selection" width="55" align="center" :selectable="isSelectable"/>
        <el-table-column label="路径名称" align="left" prop="pathName" >
        </el-table-column>
        <el-table-column label="路径类型" align="center" prop="pathType" >
          <template v-slot="scope">
            <el-tag v-if="scope.row.pathType === '1'" type="success">文件夹</el-tag>
            <el-tag v-if="scope.row.pathType === '2'" type="danger">材质（{{ formatPathFormat(scope.row.pathFormat) }}）</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="pathStatus" >
          <template v-slot="scope">
            <dict-tag :options="dict.type.sys_status" :value="scope.row.pathStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['business:pathRel:edit']"
            >修改</el-button>
            <el-button
              type="text"
              icon="el-icon-plus"
              @click="handleAdd(scope.row)"
              v-if="scope.row.pathType === '1'"
              v-hasPermi="['business:pathRel:add']"
            >新增</el-button>
            <el-button
              type="text"
              :icon="scope.row.pathStatus === 'DELETED' ? 'el-icon-refresh-left' : 'el-icon-delete'"
              @click="handleChangeStatus(scope.row)"
              v-hasPermi="['business:pathRel:changeStatus']"
            >{{scope.row.pathStatus === 'DELETED' ? "恢复" : "删除" }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加或修改路径关系对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级名称" prop="parentId">
          <treeselect v-model="form.parentId" :options="pathRelOptions" :normalizer="normalizer" placeholder="请选择上级名称" />
        </el-form-item>
        <el-form-item label="路径类型" prop="pathType">
          <el-select v-model="form.pathType" placeholder="请选择路径类型" clearable style="width: 100%" @change="typeSelectChange">
            <el-option label="文件夹" value="1"></el-option>
            <el-option label="材质" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="form.pathType === '2' ? '材质名称' : '路径名称'" prop="pathName">
          <el-input v-if="form.pathType === '1' || form.pathType === null || form.pathType === ''" v-model="form.pathName" clearable placeholder="请输入路径名称" />
          <el-select v-if="form.pathType === '2'" v-model="form.pathName" placeholder="请选则材质" filterable clearable style="width: 100%">
            <el-option v-for="item in matMgmtList" :key="item.id" :label="item.matName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="拷图格式" prop="pathFormat" v-if="form.pathType === '2'">
          <el-select  v-model="form.pathFormat" placeholder="请选则拷图格式" multiple filterable clearable style="width: 100%">
            <el-option label="源文件" value=".source" />
            <el-option label="JPG" value=".jpg"/>
            <el-option label="PNG" value=".png"/>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" clearable type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPathRel, getPathRel, delPathRel, addPathRel, updatePathRel, refreshCache, updateChangeStatus } from "@/api/business/pathRel";
import { getNormalMatMgmtList } from "@/api/business/matMgmt"
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import ResizeMixin from "@/layout/mixin/ResizeHandler";

export default {
  name: "PathRel",
  components: { Treeselect },
  mixins: [ResizeMixin],
  dicts: ['sys_status'],
  data() {
    return {
      // div高度
      divHeight: 0,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 非单个禁用
      single: true,
      // 路径关系表格数据
      pathRelList: [],
      // 路径关系树选项
      pathRelOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        pathName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级名称不能为空", trigger: "change"}
        ],
        pathType: [
          { required: true, message: "路径类型不能为空", trigger: "change" }
        ],
        pathName: [
          { required: true, message: "路径名称不能为空", trigger: "blur" },
          { required: true, message: "材质名称不能为空", trigger: "change" }
        ],
        pathFormat: [
          { required: true, message: "拷图格式不能为空", trigger: "blur" }
        ],
      },
      // 材质列表
      matMgmtList: [],
      //树结构选中数据存储
      ids: [],
    };
  },
  created() {
    this.getList();
    this.getNormalMatMgmtList();
  },
  methods: {
    /** 查询路径关系列表 */
    getList() {
      this.loading = true;
      listPathRel(this.queryParams).then(response => {
        this.pathRelList = this.$handleTree(response.data, "id", "parentId");
        this.loading = false;
      });
    },
    /** 转换路径关系数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.pathName,
        children: node.children
      };
    },
	  /** 查询路径关系下拉树结构 */
    getTreeselect() {
      listPathRel().then(response => {
        this.pathRelOptions = [];
        const filteredData = response.data.filter(item => item.pathType !== '2');
        const data = { id: 0, pathName: '顶级节点', children: [] };
        data.children = this.$handleTree(filteredData, "id", "parentId");
        this.pathRelOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: null,
        ancestors: null,
        pathName: null,
        pathFormat: null,
        pathType: null,
        pathStatus: null,
        userId: null,
        deptId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.$resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.id) {
        this.form.parentId = row.id;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加路径关系";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.parentId;
      }
      getPathRel(row.id).then(response => {
        this.form = response.data;
        if (this.form.pathFormat) {
          this.form.pathFormat = this.form.pathFormat.split(',');
        }
        this.open = true;
        this.title = "修改路径关系";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePathRel(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPathRel(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('注意：此删除不可恢复，是否确认删除？').then(function() {
        return delPathRel(ids);
      }).then(() => {
        this.ids = [];
        this.single = true;
        this.getList();
        this.$modal.msgSuccess("删除成功");

      }).catch(() => {});
    },
    /** 材质列表 */
    getNormalMatMgmtList() {
      getNormalMatMgmtList().then(res => {
        this.matMgmtList = res.data
      })
    },
    /** 路径类型选则触发 */
    typeSelectChange(val){
      this.form.pathName = null;
    },
    /** 刷新缓存 */
    handleRefreshCache(){
      refreshCache().then(() => {
        this.$modal.msgSuccess("刷新成功");
      });
    },
    /** 删除或恢复按钮操作 */
    handleChangeStatus(row) {
      const ids = row.id;
      let status = row.pathStatus === 'NORMAL'? '删除' : '恢复';
      this.$modal.confirm('是否确认' + status + '此数据项？').then(function() {
        row.pathStatus = row.pathStatus === 'NORMAL'? 'DELETED' : 'NORMAL';
        return updateChangeStatus(ids, row.pathStatus)
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(status + "成功");
      }).catch(() => {});
    },
    /** 递归选中子节点 */
    selectChildren(row, selected, disabled) {
      const nodeQueue = []; // 创建节点队列
      const childrenIds = []; // 树结构children内的id
      nodeQueue.push(...row.children);  // 初始添加第一层子节点

      // 使用while循环替代递归
      while (nodeQueue.length  > 0) {
        const currentNode = nodeQueue.shift();  // 取出队列首部节点
        this.$refs.pathTreeTable.toggleRowSelection(currentNode,  selected);
        currentNode.disabled  = disabled;
        childrenIds.push(currentNode.id);

        // 将子节点加入队列
        if (currentNode.children  && currentNode.children.length  > 0) {
          nodeQueue.push(...currentNode.children);
        }
      }

      if (selected){
        this.ids.push(row.id)
      }else {
        this.ids = this.ids.filter(id => id !== row.id)
      }

      // 过滤掉this.ids 中与childrenIds重合的id
      this.ids  = this.ids.filter(id  => !childrenIds.includes(id));
      this.single = this.ids.length!==1
    },

    /** 父节点选中事件 */
    handleRowSelect(selection, row) {
      const isSelected = selection.includes(row); // 判断父节点是否被选中
      if (row.children && row.children.length > 0) {
        this.selectChildren(row, isSelected, isSelected); // 递归设置子节点的 disabled 状态
      }else {
        if (isSelected){
          this.ids.push(row.id)
        }else {
          this.ids = this.ids.filter(id => id !== row.id)
        }
        this.single = this.ids.length!==1
      }
    },
    // 动态设置行是否可选中
    isSelectable(row) {
      return !row.disabled; // 如果 row.disabled 为 true，则不可选中
    },
    /** 格式化材质名称 */
    formatPathFormat(pathFormat) {
      const formatMap = {
        '.source': '源文件',
        '.png': 'PNG',
        '.jpg': 'JPG'
      };
      return pathFormat.split(',').map(format => formatMap[format] || format).join(', ');
    },
  }
};
</script>
